package com.share.tool.generator.sql_convert.util;

import com.share.common.constant.DirConstant;
import com.share.common.utils.FileUtil;
import com.share.common.utils.StrUtil;
import com.share.tool.generator.sql_convert.vo.Column;
import com.share.tool.generator.sql_convert.vo.Table;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

/**
 * 必须是标准的从数据库中导出的sql 或者 表结构
 * <p>
 * 把sql 或者表结构 文件转换为对应的 java model文件
 */
@Slf4j
public class ReadUtil {
    /**
     * 必须是标准的从数据库中导出的sql表结构
     *
     * @return
     */
    public static List<Table> readTableStructure() {
        String filePath = DirConstant.TMP_DIR + File.separator + "table_structure_sql.txt";
        List<String> lineList = FileUtil.readByLine(new File(filePath));
        List<Table> list = new LinkedList<>();

        Table table = null;
        List<Column> listColumn = null;
        for (String line : lineList) {
            if (StringUtils.isBlank(line)) {
                continue;
            }

            line = line.trim();
            if (line.startsWith("/*")) {
                log.error("清除表开头的注释");
                throw new RuntimeException("sql语句异常");
            }

            if (line.startsWith("--") || line.startsWith("DROP TABLE") || line.startsWith("SET ") || line.startsWith("PRIMARY KEY ") || line.startsWith("INDEX ")) {
                continue;
            }

            //冗余多空格处理
            line = line.replaceAll("  ", " ").replaceAll("  ", " ").replaceAll("  ", " ");
            String[] split = line.split(" ");
            if (split.length < 3) {
                continue;
            }

            //提取表明
            if (line.contains("CREATE ") && line.contains(" TABLE")) {
                String tableName = StrUtil.trim(split[2], '`');
                listColumn = new LinkedList<>();
                table = new Table(tableName, listColumn);
                list.add(table);
                continue;
            }

            //表注释
            if (line.contains("ENGINE ")) {
                int comment = StrUtil.indexOf(line, "COMMENT", "'");
                if (comment >= 0) {
                    String st = line.substring(comment);
                    String[] s = st.split(" ");
                    String tableComment = s[0];
                    table.setTableComment(tableComment);
                    continue;
                }
            }

            Column c = new Column();
            listColumn.add(c);

            String name = split[0];
            String type = split[1];
            if ("timestamp".equals(type)) {
                type = "";
            }

            boolean isnull = true;
            if (line.contains(" NOT ")) {
                isnull = false;
            } else {
                isnull = true;
            }

            String comment = null;
            if (line.contains("COMMENT")) {
                comment = split[split.length - 1];
            }


            comment = StrUtil.trim(comment, '\'');
            if (comment == null || "null".equals(comment.toLowerCase())) {
                comment = "";
            }
            c.setComment(comment);

            c.setColumn(StrUtil.trim(name, '`'));
            c.setColumnCamel(c.getColumn());
            c.setType(type);
            c.setIsNull(isnull);
        }

        return list;
    }

    public static List<Table> readInsertSql() {
        String filePath = DirConstant.TMP_DIR + File.separator + "insert_sql.txt";
        List<String> list = FileUtil.readByLine(new File(filePath));
        List<Table> reList = new LinkedList<>();
        for (String line : list) {
            //空行
            line = line.trim();
            if (StringUtils.isBlank(line)) {
                continue;
            }

            //INSERT INTO `stockj`.`stock_zh_a_spot_em` (`id`, `seq`, ive_ratio`) VALUES (1, NULL, NULL, NULL, NULL);
            //创建表-开始字符-识别
            String[] values = line.split("VALUES");
            String insertHeader = values[0].replaceAll("`", "");

            //提取field
            int c1 = insertHeader.indexOf("(");
            int c2 = insertHeader.indexOf(")");
            String strField = insertHeader.substring(c1 + 1, c2);
            String[] fields = strField.split(",");

            //提取表名字
            int t1 = insertHeader.indexOf(".");
            if (t1 < 0) {
                String into = "INTO ";
                t1 = insertHeader.indexOf(into) + into.length();
                if (t1 < 0) {
                    t1 = insertHeader.indexOf(into.toLowerCase()) + into.length();
                }
            } else {
                t1 = t1 + 1;
            }
            String tableName = insertHeader.substring(t1, c1).trim();

            List<Column> coulmnList = new LinkedList<>();
            int len = fields.length;
            for (int j = 0; j < len; j++) {
                String coulmn = fields[j].trim();
                coulmnList.add(new Column(coulmn));
            }

            reList.add(new Table(tableName, coulmnList));
        }
        return reList;
    }

    public static void main(String[] args) {
        List<Table> list = readInsertSql();
    }
}


